<template>
  <app-dialog-form
    :title="props.articleId ? '编辑公告' : '新增公告'"
    :confirm="handleDialogSubmit"
    @closed="handleDialogClose"
    @open="handleDialogOpen"
  >
    <el-form
      class="el-form--label-top"
      ref="form"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
    >
      <el-form-item
        label="标题"
        prop="name"
      >
        <el-input
          v-model="formData.title"
          placeholder="名称"
        />
      </el-form-item>
      <el-form-item
        label="类型"
        prop="type"
      >
        <el-input
          v-model="formData.type"
          placeholder="请输入类型"
        />
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
          v-model="formData.isShow"
        />
      </el-form-item>
      <el-form-item
        label="内容"
        prop="content"
      >
        <el-input
          v-model="formData.content"
          placeholder="请输入公告内容"
        />
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import type { PropType } from 'vue'
import { addArticle, getArticleList } from '@/api/cms'
import type { IElForm, IFormItemRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const form = ref<IElForm | null>(null)
const formLoading = ref(false)

const formData = ref({
  content: '',
  isShow: '',
  title: '',
  type: '',
  id: ''
})

const props = defineProps({
  articleId: {
    type: Number as PropType<number | null>,
    default: null
  }
})

const formRules: IFormItemRule = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  isShow: [
    { required: false, message: '请输入分类编号', trigger: 'blur' }
  ],
  type: [
    { required: false, message: '请输入类型', trigger: 'blur' }
  ]
}

interface EmitType {
  (e: 'update:article-id', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitType>()

const handleDialogSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  if (props.articleId) {
  // 编辑
    formData.value.id = props.articleId + ''
  }
  await addArticle(formData.value)
  emit('success')
  ElMessage.success('保存成功')
}

// 打开表单 加载 数据
const handleDialogOpen = () => {
  loadArticleList()
}

const loadArticleList = async () => {
  if (!props.articleId) {
    return
  }
  formLoading.value = true
  const data = await getArticleList({ id: props.articleId }).finally(() => {
    formLoading.value = false
  })
  const updata = data.data.result[0]
  formData.value = updata
}

const handleDialogClose = () => {
  emit('update:article-id', null)
  // 清楚 form 表单 必须包含 form 必须包含 ref="form"
  formData.value.title = ''
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

</script>

<style lang="scss" scoped>
</style>
